package com.optionexplorer.data;

import java.util.logging.Logger;

import com.optionexplorer.util.NetUtils;
import com.optionexplorer.util.StringUtils;

/**
 * Class retrieves the quote for a given option symbol from Yahoo
 * @author kgajjala
 *
 */

public class YahooDividendImpl implements DividendIfc {

	private static final Logger Log = Logger.getLogger(YahooDividendImpl.class.getName());
	public static String STOCK_BASE_URL = "http://finance.yahoo.com/q/ks?s=";
	public static String ETF_BASE_URL = "http://finance.yahoo.com/q/pr?s=";
	private String quote = null;
	private float divRate = 0;
	public static final String FORWARD_DIVIDEND_STR = "Forward Annual Dividend Rate";
	public static final String TRAILING_DIVIDEND_STR = "Trailing Annual Dividend Rate";
	
	
	public YahooDividendImpl(String q) {
		this.quote = q;
	}
	
	private void getStockDividendAmount(String pattern) {
		
		String url = STOCK_BASE_URL + this.quote;
		StringBuilder sb = NetUtils.getPageFromWeb(url);
		int index1, index2 = 0;
		
		index1 = sb.indexOf(pattern);
		if (index1 < 0) {	
			Log.info("Could not find the pattern Forward Annual Dividend Rate in url : " + url);
			return;
		}
		
		index1 = sb.indexOf("<td", index1);
		index2  = sb.indexOf("</td>", index1);
		String str = sb.substring(index1, index2+4);
		str = StringUtils.stripHTML(str);
		this.divRate = StringUtils.strToFloat(str);		
				
		return;
	}

	private void getETFDividendAmount() {
		
		String url = ETF_BASE_URL + this.quote;
		StringBuilder sb = NetUtils.getPageFromWeb(url);
		int index1, index2 = 0;
		
		index1 = sb.indexOf("Yield:");
		if (index1 < 0) {	
			Log.severe("Could not find the pattern Yield in url : " + url);
			Log.severe(sb.toString());
			return;
		}
		
		index1 = sb.indexOf("<td", index1);
		index2  = sb.indexOf("</td>", index1);
		String str = sb.substring(index1, index2+4);
		str = StringUtils.stripHTML(str);
		this.divRate = StringUtils.strToFloat(str.substring(0, str.length()-1));		
		return;
	}
	
	public float getDividendAmount() {
		getStockDividendAmount(FORWARD_DIVIDEND_STR);
		if (this.divRate == 0) {
			getStockDividendAmount(TRAILING_DIVIDEND_STR);
		}
		if (this.divRate == 0) {
			getETFDividendAmount();
		}
		
		return this.divRate;
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		YahooDividendImpl v = new YahooDividendImpl("VZ");
		System.out.println("VZ : " + v.getDividendAmount());
		v = new YahooDividendImpl("NLY");
		System.out.println("NLY : " + v.getDividendAmount());
		v = new YahooDividendImpl("NLR");
		System.out.println("NLR : " + v.getDividendAmount());
		
	}

}
